import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';

import {
  logout as abpLogout,
  getCurrentLoginInformation,
  getUserPermissions,
  login,
} from '#/api/abp';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;

      const reqLogin = {
        username: params.username,
        password: params.password,
      };
      // 使用ABP的登录API
      const loginResult = await login(reqLogin);

      // 如果成功获取到 accessToken
      if (loginResult.access_token) {
        accessStore.setAccessToken(loginResult.access_token);
        accessStore.setRefreshToken(loginResult.refresh_token);

        // 设置token过期时间
        if (loginResult.expire_in) {
          const expiresAt = Date.now() + loginResult.expire_in * 1000;
          localStorage.setItem('expire_in', expiresAt.toString());
        }

        // 获取用户信息并存储到 accessStore 中
        const [fetchUserInfoResult] = await Promise.all([
          fetchUserInfo(),
        ]);
        userInfo = fetchUserInfoResult;
        if (userInfo) {
          if (accessStore.loginExpired) {
            accessStore.setLoginExpired(false);
          } else {
            onSuccess
              ? await onSuccess?.()
              : await router.push(
                userInfo.homePath || preferences.app.defaultHomePath,
              );
          }

          if (userInfo?.realName) {
            notification.success({
              description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
              duration: 3,
              message: $t('authentication.loginSuccess'),
            });
          }
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    // try {
    //   // 使用ABP的登出API
    //   await abpLogout();
    // } catch {
    //   // 不做任何处理
    // }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
          redirect: encodeURIComponent(router.currentRoute.value.fullPath),
        }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;

    // 使用ABP的获取当前用户信息API
    const applicationConfiguration = (await getCurrentLoginInformation());
    const abpUserInfo = applicationConfiguration.currentUser;
    const permissions = applicationConfiguration.auth.grantedPolicies;

    // 设置用户权限
    const permissionList = Object.keys(permissions || {}).filter(
      (key) => permissions?.[key] === true,
    );
    if (permissionList.length == 0) { //没有权限则到登录页面
      accessStore.setLoginExpired(false);
      accessStore.accessToken=null;
    }
    // 转换ABP用户信息到系统需要的格式
    if (abpUserInfo) {
      userInfo = {
        userId: abpUserInfo.id,
        username: abpUserInfo.userName,
        realName: abpUserInfo.name,
        avatar: 'apps/web-antd/public/avatar-v1.webp', // ABP默认没有用户头像，需要自行实现
        desc: '',
        email: abpUserInfo.email,
        homePath: '/dashboard',
        roles: abpUserInfo.roles || [],
        permissions: permissionList || [],
        token: accessStore.accessToken || '',
      };
    }

    if (userInfo) {
      userStore.setUserInfo(userInfo);
      accessStore.setAccessCodes(
        userInfo.permissions || [],
      );
    }
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
